$(function () {
  let layer = layui.layer;
  getTalk();
  $('.submit').click(() => {
    postTalk();
  });
  function getTalk() {
    let id = location.href.split('?')[1];
    $.ajax({
      url: `/api/articles/${id}/comments`,
      success(res) {
        let str = template('comment', res);
        $('.kr_comment_wrap').html(str);
      },
    });
  }
  function postTalk() {
    let id = location.href.split('?')[1];
    let data = {
      content: $('.form textarea').val().trim(),
      uname: '张三',
    };
    if (!data.content) return layer.msg('请输入内容');
    $.ajax({
      type: 'POST',
      url: `/api/articles/${id}/comments`,
      data,
      success(res) {
        if (res.status != 0) return layer.msg(res.message);
        layer.msg(res.message);
        getTalk();
      },
    });
  }
  let getZero = (num) => (num > 10 ? num : '0' + num);
  template.defaults.imports.filterTime = function (res) {
    let date = new Date(res);
    let y = date.getFullYear();
    let m = getZero(date.getMonth() + 1);
    let d = getZero(date.getDate());
    return `${y}-${m}-${d}`;
  };
});
